import { Component, OnInit, ViewChild } from '@angular/core';
import { DatatableComponent, PageConfig } from '@iux/live';
import { map as _map, remove as _remove } from 'lodash';

@Component({
  selector: 'app-demo3',
  templateUrl: './demo3.component.html',
  styles: [
    `
      lv-paginator {
        margin-left: 16px;
      }
    `
  ]
})
export class Demo3Component implements OnInit {
  sourceData = [];
  targetData = [];
  selection = [];
  total = 100;

  @ViewChild('lvTable') lvTable: DatatableComponent;

  constructor() {}

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.sourceData = this.getSourceData({ pageIndex: 0, pageSize: 5 });
    this.targetData = [...this.selection];
  }

  getSourceData(page) {
    return Array.from({ length: page.pageSize }).map((item, key) => {
      return {
        key: key + 1 + page.pageIndex * page.pageSize,
        site: `site${key + 1 + page.pageIndex * page.pageSize}`,
        type: key % 2 === 0 ? 'AP' : 'ZP',
        destination: ''
      };
    });
  }

  pageChange(source: PageConfig) {
    this.sourceData = this.getSourceData(source);
  }

  selectionChange(selection, belong) {
    this.targetData = [...selection];
    if (belong === 'target') {
      this.lvTable.setData(this.targetData);
    }
  }

  remove(source) {
    const deleteKeys = _map([source], 'key');
    _remove(this.selection, item => deleteKeys.includes(item.key));
    this.targetData = this.selection = [...this.selection];
  }
}
